<template>
	<div class="ai-chat-container">
		<div class="chat-header">
			<h2>AI 智能助手</h2>
		</div>

		<div class="chat-messages" ref="messagesContainer">
			<div
				v-for="(message, index) in messages"
				:key="index"
				:class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
			>
				<div class="message-avatar">
					<div class="avatar-icon">{{ message.role === 'user' ? '👤' : '🤖' }}</div>
				</div>
				<div class="message-content">
					<div v-if="message.role === 'user'" v-html="message.content"></div>
					<div v-else>
						<div v-if="message.isStreaming" class="typing-indicator">
							<span></span><span></span><span></span>
						</div>
						<div v-else v-html="formatMarkdown(message.content)"></div>
					</div>
				</div>
			</div>
		</div>

		<div class="chat-input">
			<textarea
				v-model="userInput"
				@keydown.enter.prevent="sendMessage"
				placeholder="有什么想问的问题？按Enter发送..."
				rows="2"
			></textarea>
			<button @click="sendMessage" :disabled="isLoading" class="send-button">
				<i class="send-icon">{{ isLoading ? '⏳' : '➤' }}</i>
			</button>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { getAiAnswerService } from '@/api/ai'

// 定义消息类型
interface Message {
	role: string
	content: string
	isStreaming: boolean
}

// 配置marked使用highlight.js进行代码高亮
marked.setOptions({
	highlight: function (code: string, lang: string) {
		if (lang && hljs.getLanguage(lang)) {
			return hljs.highlight(code, { language: lang }).value
		}
		return hljs.highlightAuto(code).value
	},
	breaks: true
} as any)

const userInput = ref('')
const messages = ref<Message[]>([
	{
		role: 'assistant',
		content: '你好！我是AI智能助手，请问有什么我可以帮助你的？',
		isStreaming: false
	}
])
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)

// 格式化Markdown内容
function formatMarkdown(text: string) {
	return marked(text)
}

// 滚动到底部
function scrollToBottom() {
	nextTick(() => {
		if (messagesContainer.value) {
			messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
		}
	})
}

// 监听消息变化，自动滚动到底部
watch(
	messages,
	() => {
		scrollToBottom()
	},
	{ deep: true }
)

// 模拟打字效果
function simulateTyping(text: string, aiMessageIndex: number) {
	return new Promise<void>((resolve) => {
		let currentText = ''
		const words = text.split('')
		let i = 0

		const typingInterval = setInterval(() => {
			if (i < words.length) {
				currentText += words[i]
				messages.value[aiMessageIndex] = {
					...messages.value[aiMessageIndex],
					content: currentText
				}
				i++
			} else {
				clearInterval(typingInterval)
				resolve()
			}
		}, 15) // 调整打字速度
	})
}

// 发送消息
async function sendMessage() {
	if (!userInput.value.trim() || isLoading.value) return

	// 添加用户消息
	messages.value.push({
		role: 'user',
		content: userInput.value,
		isStreaming: false
	})

	// 添加AI助手的占位消息（用于显示打字指示器）
	const aiMessageIndex = messages.value.length
	messages.value.push({
		role: 'assistant',
		content: '',
		isStreaming: true
	})

	// 清空输入框
	const userMessage = userInput.value
	userInput.value = ''
	isLoading.value = true

	try {
		// 调用API获取AI回答
		const response = await getAiAnswerService({ userId: 1, content: userMessage })

		if (response && response.data.code === 1 && response.data.data) {
			// 模拟流式响应
			await simulateTyping(response.data.data, aiMessageIndex)
		} else {
			throw new Error('无效的响应数据')
		}

		// 完成流式传输
		messages.value[aiMessageIndex].isStreaming = false
	} catch (error) {
		console.error('获取AI响应时出错:', error)
		messages.value[aiMessageIndex] = {
			role: 'assistant',
			content: '抱歉，发生了错误，请稍后再试。',
			isStreaming: false
		}
	} finally {
		isLoading.value = false
	}
}

onMounted(() => {
	scrollToBottom()
})
</script>

<style scoped>
.ai-chat-container {
	display: flex;
	flex-direction: column;
	height: 80vh;
	max-width: 900px;
	margin: 0 auto;
	border-radius: 12px;
	overflow: hidden;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
	background-color: #fff;
}

.chat-header {
	padding: 18px 24px;
	background: linear-gradient(135deg, #6366f1, #8b5cf6);
	color: white;
	border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.chat-header h2 {
	margin: 0;
	font-size: 1.3rem;
	font-weight: 600;
}

.chat-messages {
	flex: 1;
	overflow-y: auto;
	padding: 24px;
	background-color: #f9fafb;
}

.message {
	display: flex;
	margin-bottom: 20px;
	animation: fadeIn 0.3s ease-in-out;
}

.message-avatar {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	margin-right: 12px;
	flex-shrink: 0;
}

.avatar-icon {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100%;
	border-radius: 50%;
	font-size: 18px;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.user-message .avatar-icon {
	background: linear-gradient(135deg, #3b82f6, #60a5fa);
	color: white;
}

.ai-message .avatar-icon {
	background: linear-gradient(135deg, #10b981, #34d399);
	color: white;
}

.message-content {
	padding: 14px 18px;
	border-radius: 18px;
	max-width: 75%;
	word-break: break-word;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.user-message .message-content {
	background: linear-gradient(135deg, #3b82f6, #60a5fa);
	color: white;
	margin-left: auto;
	border-bottom-right-radius: 4px;
}

.ai-message .message-content {
	background-color: white;
	border-bottom-left-radius: 4px;
}

.chat-input {
	padding: 16px 20px;
	background-color: white;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
}

.chat-input textarea {
	flex: 1;
	padding: 14px;
	border: 1px solid #e5e7eb;
	border-radius: 24px;
	resize: none;
	font-family: inherit;
	font-size: 14px;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
	transition:
		border-color 0.2s,
		box-shadow 0.2s;
}

.chat-input textarea:focus {
	outline: none;
	border-color: #6366f1;
	box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.send-button {
	width: 42px;
	height: 42px;
	margin-left: 10px;
	background: linear-gradient(135deg, #6366f1, #8b5cf6);
	color: white;
	border: none;
	border-radius: 50%;
	cursor: pointer;
	display: flex;
	align-items: center;
	justify-content: center;
	transition:
		transform 0.2s,
		background-color 0.2s;
	box-shadow: 0 2px 6px rgba(99, 102, 241, 0.3);
}

.send-button:hover:not(:disabled) {
	transform: scale(1.05);
}

.send-button:disabled {
	background: linear-gradient(135deg, #a5a6f6, #c7bef6);
	cursor: not-allowed;
}

.send-icon {
	font-style: normal;
	font-size: 16px;
}

/* 打字指示器样式 */
.typing-indicator {
	display: flex;
	align-items: center;
}

.typing-indicator span {
	height: 8px;
	width: 8px;
	background-color: #8b5cf6;
	border-radius: 50%;
	display: inline-block;
	margin-right: 5px;
	animation: bounce 1.5s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
	animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
	animation-delay: 0.4s;
	margin-right: 0;
}

@keyframes bounce {
	0%,
	60%,
	100% {
		transform: translateY(0);
	}
	30% {
		transform: translateY(-5px);
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: translateY(10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

/* Markdown内容样式 */
:deep(pre) {
	background-color: #f3f4f6;
	padding: 14px;
	border-radius: 8px;
	overflow-x: auto;
	margin: 12px 0;
}

:deep(code) {
	font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
	font-size: 0.9em;
}

:deep(p) {
	margin: 0.7em 0;
	line-height: 1.6;
}

:deep(ul),
:deep(ol) {
	padding-left: 1.5em;
	margin: 0.7em 0;
	line-height: 1.6;
}

:deep(a) {
	color: #6366f1;
	text-decoration: none;
	border-bottom: 1px solid #6366f1;
}

:deep(a:hover) {
	opacity: 0.8;
}

:deep(blockquote) {
	border-left: 4px solid #8b5cf6;
	padding: 8px 16px;
	margin: 12px 0;
	background-color: #f9f9ff;
	border-radius: 0 8px 8px 0;
}

:deep(table) {
	border-collapse: collapse;
	width: 100%;
	margin: 12px 0;
	border-radius: 8px;
	overflow: hidden;
}

:deep(th),
:deep(td) {
	border: 1px solid #e5e7eb;
	padding: 10px;
	text-align: left;
}

:deep(th) {
	background-color: #f3f4f6;
}

:deep(h1),
:deep(h2),
:deep(h3),
:deep(h4),
:deep(h5),
:deep(h6) {
	margin-top: 20px;
	margin-bottom: 10px;
	font-weight: 600;
	color: #111827;
}
</style>
